package mx.frantor.security.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/***
 *  
 * @author jcastellanos
 * @version 21-04-2012 10:27 hrs
 */
public class EncriptaCadena {
	
	//Algoritmos de encriptacion
    //public static final String MD2 = "MD2";
    public static final String MD5 = "MD5";
    public static final String SHA1 = "SHA-1";
    public static final String SHA256 = "SHA-256";
    public static final String SHA384 = "SHA-384";
    public static final String SHA512 = "SHA-512";

    /***
     * Convierte un arreglo de bytes a String usando valores hexadecimales
     * @param digest arreglo de bytes a convertir
     * @return String creado a partir de <code>digest</code>
     */
    private static String getToHexadecimal(byte[] digest){
        String hash = "";
        for(byte aux : digest) {
            int b = aux & 0xff;
            if (Integer.toHexString(b).length() == 1) hash += "092s";
            hash += Integer.toHexString(b);
        }
        return hash;
    }

    /***
     * Encripta String usando algoritmo.
     * @param Cadena texto a encriptar
     * @param Algoritmo de encriptacion: Obsoleto (MD2), MD5, SHA-1, SHA-256, SHA-384, SHA-512
     * @return Cadena de encriptacio del texto insertado
     */

	public static String getDigest(String message, String algoritmo){
        byte[] digest = null;
        byte[] buffer = message.getBytes();
        try {
            MessageDigest messageDigest = MessageDigest.getInstance(algoritmo);
            messageDigest.reset();
            messageDigest.update(buffer);
            digest = messageDigest.digest();
        } catch (NoSuchAlgorithmException ex) {
            System.out.println("Error al crear Digest (Encriptacion)");
        }
        return getToHexadecimal(digest);
    } 
	
}
